import styles from "@/styles/confirmmodal.module.scss";
import { useState, forwardRef, useImperativeHandle } from "react";

interface Props {
  type: "success" | "error" | "warning" | "info";
  text?: string;
  onCancel?: () => void;
  onConfirm: (callback: () => void) => void;
}

const ConfirmModal = (props: Props, ref: any) => {
  const TYPE_ICONS = {
    success: "✅",
    error: "❌",
    warning: "☣️",
    info: "ℹ️",
  };

  const TYPE_TITLES = {
    success: "成功",
    error: "错误",
    warning: "警告",
    info: "信息",
  };

  const DEFAULT_TYPES = "warning";

  const [open, setOpen] = useState(false);

  useImperativeHandle(ref, () => ({
    open: () => {
      setOpen(true);
    },
    close: () => {
      setOpen(false);
    },
  }));

  return (
    <>
      {open ? (
        <div className={styles.container} data-testid="confirm-modal">
          <div className={styles.content}>
            <div className={styles.title}>
              <span className="text-2xl">
                {TYPE_ICONS[props.type || DEFAULT_TYPES]}
              </span>
              <span className="text-xl">
                {TYPE_TITLES[props.type || DEFAULT_TYPES]}
              </span>
            </div>
            <p className="pl-8 pr-8 mt-1 text-xl text-current">
              {props.text || "是否继续执行此操作?"}
            </p>

            <div className="flex flex-row-reverse">
              <div
                onClick={(e) => {
                  e.stopPropagation();
                  setOpen(false);
                  props.onCancel && props.onCancel();
                }}
                className={styles.btncancel}
                data-testid="confirm-modal-cancel"
              >
                取消
              </div>
              <div
                onClick={(e) => {
                  e.stopPropagation();
                  props.onConfirm(() => setOpen(false));
                }}
                className={styles.btnconfirm}
                data-testid="confirm-modal-confirm"
              >
                确认
              </div>
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
};

export default forwardRef(ConfirmModal);
